package org.vnl.platform.orm;

import java.util.HashMap;

import org.apache.log4j.Logger;

/**
 * 用以儲存一個或多個Persistence Manager
 * 
 * @author Vaughan
 *
 */
public class PersistenceManagerFactory {
    private static final Logger logger = Logger.getLogger(PersistenceManagerFactory.class);

    private static PersistenceManagerFactory instance;
    
    private HashMap<String, IPersistenceManager> pools;
    
    private static final ThreadLocal<IPersistenceManager> currentPM = new ThreadLocal<IPersistenceManager>();
    
    private PersistenceManagerFactory() {
        pools = new HashMap<String, IPersistenceManager>();
    }
    
    public static PersistenceManagerFactory getInstance() {
        if (instance == null) {
            instance = new PersistenceManagerFactory();
        }
        return instance;
    }
    
    public IPersistenceManager getPM(String name) {
        IPersistenceManager pm = this.pools.get(name);
        if (pm == null) {
            logger.fatal("Persistence Manager("+name+") does not initialize properly.");
            throw new RuntimeException("Persistence Manager("+name+") does not initialize properly.");
        }
        currentPM.set(pm);
        return pm;
    }
    
    public void addPM(String name, IPersistenceManager pm) {
        if (this.pools.get(name) != null) {
            logger.fatal("Persistence Manager("+name+") already exist.");
            throw new RuntimeException("Persistence Manager("+name+") already exist.");
        }
        this.pools.put(name, pm);
    }
    
    public IPersistenceManager getCurrentPM() {
        if (currentPM.get() == null) {
            throw new TransactionException(TransactionErrCode.ERR_CURRENT_PM_NOT_SET);
        }
        return currentPM.get();
    }
    
    public void closeCurrentPM() {
        currentPM.set(null);
    }
}
